package com.yx.cloud.activity;

import static com.iot.common.utils.Event.MESSAGE_TYPE_GET_CLEAN_RECORD;

import android.animation.Animator;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.iot.common.utils.LogUtils;
import com.iot.sdk.yugong.resp.YuGongRespDataList;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.GetCleanRecordParam;
import com.yx.cloud.Interface.BounceCallBack;
import com.yx.cloud.Interface.EventForwardingHelper;
import com.yx.cloud.R;
import com.yx.cloud.adapter.CleanRecordAdapter;
import com.yx.cloud.header.NormalBounceHandler;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.StatusBarColorUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.BounceLayout;
import com.yx.cloud.view.DefaultHeader;
import com.iot.product.sweeper.bean.CleanRecord;
import com.iot.product.sweeper.bean.CleanStatistics;
import com.iot.product.sweeper.bean.Robot;
import com.iot.common.utils.Event;

import java.util.ArrayList;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;


/**
 * 清扫记录界面
 */
public class CleanRecordActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "CleanRecordActivity";
    private static final int PAGE_SIZE = 10;

    CleanRecordAdapter cleanRecordAdapter;
    List<CleanRecord> cleanRecords;
    private int offset = 0;
    private Robot robot;
    private boolean isLoadMore = false;
    private LoadProgressDialog loadProgressDialog;
    //    private CleanrecordActivityBinding binding;
//    private CleanrecordActivityNoHeadBinding noHeadBinding;
    private JSONObject productConfig;

    BounceLayout bl;
    TextView tvTotalTime, tvTotalArea, tvTotalDegree;
    ListView cleanRecordListview;
    ImageView ivCleanRecordReturn;
    RelativeLayout rlNoMessage;
    LinearLayout llCleanRecordTitle;
    FrameLayout flRoot;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorUtils.fullScreen(this);//导航栏变透明了
//        LanguageUtils.getAndsetLanguage(this, "清扫记录");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        robot = AppContext.get().getCurrentDevice();
        productConfig = AppContext.getConfig();
        if (!productConfig.optBoolean(ProductConfigConstants.cleanRecordHead, false)) {
            setContentView(R.layout.cleanrecord_activity_no_head);
        } else {
            setContentView(R.layout.cleanrecord_activity);
        }
        initView();
        initData();
        initEvent();
        if (productConfig.optBoolean(ProductConfigConstants.cleanRecordHead)) {
            int barHeight = StatusBarColorUtils.getStatusBarHeight(this);
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) llCleanRecordTitle.getLayoutParams();
            lp.setMargins(0, barHeight, 0, 0);
            llCleanRecordTitle.setLayoutParams(lp);
        }
        showLoadingDialog();
        refreshCleanRecord();
        getCleanRecordStatistics();
    }

    private void initView() {
        ivCleanRecordReturn = findViewById(R.id.iv_cleanRecordReturn);
        bl = findViewById(R.id.bl);
        tvTotalTime = findViewById(R.id.tv_totalTime);
        tvTotalArea = findViewById(R.id.tv_totalArea);
        tvTotalDegree = findViewById(R.id.tv_totalDegree);
        cleanRecordListview = findViewById(R.id.cleanRecord_listview);
        rlNoMessage = findViewById(R.id.rl_noMessage);
        llCleanRecordTitle = findViewById(R.id.ll_cleanRecordTitle);
        flRoot = findViewById(R.id.fl_root);
    }


    private void initData() {

        bl.setBounceHandler(new NormalBounceHandler(), cleanRecordListview);//设置滚动冲突的控制类
        bl.setEventForwardingHelper(new EventForwardingHelper() {//自定义事件分发处理
            @Override
            public boolean notForwarding(float downX, float downY, float moveX, float moveY) {
                return true;
            }
        });
        bl.setHeaderView(new DefaultHeader(this), flRoot);//设置刷新头，null意味着没有刷新头，不调用该函数意为着空
        //bl.setFooterView(new DefaultFooter(this), flRoot);//上拉

        if (!productConfig.optBoolean(ProductConfigConstants.cleanRecordHead)) {
            StatusBarColorUtils.setStatusBarFontColor(this, R.color.white, "0");//设置黑色
        } else {
            CleanStatistics cleanStatistics = robot.getCleanStatistics();
            Log.i(TAG, " : deviceId --hhhhhhhhhhhh--------------------- " + cleanStatistics.getHistoryTime());
            tvTotalTime.setText(cleanStatistics.getHistoryTime() / 3600 + "");
            tvTotalArea.setText(cleanStatistics.getHistoryArea() + "");
            tvTotalDegree.setText(cleanStatistics.getCleanCount() + "");
        }

        cleanRecords = new ArrayList<>();
        cleanRecordAdapter = new CleanRecordAdapter(CleanRecordActivity.this, cleanRecords);
        cleanRecordListview.setAdapter(cleanRecordAdapter);

        cleanRecordListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //将清扫记录数据保存在本地，跳转到详情页再读取，避免数据量太大用intent会报错
                if (!productConfig.optBoolean(ProductConfigConstants.hasMap)) {
                    return;
                }
                CleanRecord cleanRecord = cleanRecords.get(position);
                Gson gson = new Gson();
                String strGson = gson.toJson(cleanRecord);
                SharedPrefsUtil.putValue(CleanRecordActivity.this, "cleanRecordData", "recordData", strGson);
                Intent_utils.enterIntent(CleanRecordActivity.this, CleanRecordDetailActivity.class);
                Log.d(TAG, "get record success");
            }
        });

        ivCleanRecordReturn.setOnClickListener(this);

    }

    private void showLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
        loadProgressDialog = new LoadProgressDialog(this, 6);
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
                ToastUtil.showShort(CleanRecordActivity.this, R.string.U_T_NetworkTimeout);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        loadProgressDialog.show();
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_cleanRecordReturn:
                Intent_utils.backIntent(this);
                break;
        }
    }

    private void initEvent() {
        // 设置上拉加载更多
        bl.setBounceCallBack(new BounceCallBack() {
            @Override
            public void startRefresh() {
                refreshCleanRecord();
            }

            @Override
            public void startLoadingMore() {
                //loadMoreData();
            }
        });
    }

    private void loadMoreData() {
        this.isLoadMore = true;
        LogUtils.i("上拉 加载 offset ：" + offset);
        GetCleanRecordParam param = new GetCleanRecordParam();
        param.setOffset(offset);
        param.setLimit(PAGE_SIZE);
        param.setDeviceID(robot.getDeviceId());
        AppContext.getProductService().getCleanRecord(param);
    }

    private void getCleanRecordStatistics(){
        AppContext.getProductService().getCleanRecordStatistics();
    }

    private void refreshCleanRecord() {
        //获取清扫记录接口
        this.isLoadMore = false;
        offset = 0;
        GetCleanRecordParam param = new GetCleanRecordParam();
        param.setOffset(offset);
        param.setLimit(PAGE_SIZE);
        param.setDeviceID(robot.getDeviceId());
        AppContext.getProductService().getCleanRecord(param);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MSG_ROBOT_CLEANSTATISTICS:
                if(event.isResult()){
                    //清扫总时长，面积，次数
                    CleanStatistics cleanStatistics = robot.getCleanStatistics();
                    tvTotalTime.setText(cleanStatistics.getHistoryTime() / 3600 + "");
                    tvTotalArea.setText(cleanStatistics.getHistoryArea() + "");
                    tvTotalDegree.setText(cleanStatistics.getCleanCount() + "");
                }
                break;
            case MESSAGE_TYPE_GET_CLEAN_RECORD:
                hideLoadingDialog();
                // 加载完数据设置为不加载状态，将加载进度收起来
                bl.setRefreshCompleted();
                if (event.isResult()) {
                    List<CleanRecord> newCleanRecord = (List<CleanRecord>) event.getContent();
                    LogUtils.i("e  vvvvvvvv cleanRecords.size : " + newCleanRecord.size());
                    if (isLoadMore) {
                        cleanRecords.addAll(newCleanRecord);
                    } else {
                        if (cleanRecords != null) {
                            cleanRecords.clear();
                        }
                        cleanRecords = newCleanRecord;
                    }
                    offset = cleanRecords.size();

                    if (cleanRecords.size() == 0) {
                        hideListView();
                    } else {
                        showListView();
                        //有记录 但是没有新纪录
                        if (newCleanRecord.size() == 0) {
                            ToastUtil.show(CleanRecordActivity.this, getResources().getString(R.string.U_NoMoreRecords), Toast.LENGTH_SHORT);
                        }
                    }
                    cleanRecordAdapter.update(cleanRecords);
                } else {
                    hideListView();
                }
                break;

        }
    }


    private void hideLoadingDialog() {
        if (loadProgressDialog != null) {
            if (loadProgressDialog.isShowing()) {
                loadProgressDialog.dismiss();
            }
        }
    }

    private void showListView() {
        rlNoMessage.setVisibility(View.GONE);
        cleanRecordListview.setVisibility(View.VISIBLE);
    }

    private void hideListView() {
        rlNoMessage.setVisibility(View.VISIBLE);
        cleanRecordListview.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
